<?php
/**
 * Created by PhpStorm.
 * User: thorjiang
 * Date: 2018/5/10
 * Time: 00:37
 */

namespace App\Http\Services;

use App\Http\Modules\BaseMicroMsg;
use App\Models\UserModel;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

/**
 * 微信授权, 小程序,web,app通用
 * Class WeixinAuth
 * @package App\Http\Services
 */
class WeixinAuth
{
    const APP_LOGIN = 10;
    const WEB_LOGIN = 11;
    const MICRO_APP_LOGIN = 12;

    public function getOpenId($code) {
//        return ['openid' => 'oFYEA0acYjqWUq3iIbYRqlwLjBOc'];

        $r = static::microOauth2($code);
        if (!$r) {
            throwResponseException(1000, '授权获取OPENID失败');
        }

        return $r;
    }

    /**
     * @param  code
     * @param  data
     * @return array [unionid, nickname, avatar]
     */
    public function getUserProfileByMicro($r, $userInfo = [])
    {
        //$sessionKey = 'f2g0S0toVP5GjCYExZ60hg';
        $encryptedData = $userInfo['encryptedData'];
        $iv = $userInfo['iv'];

        $aesCipher = base64_decode($encryptedData);
        $aesIV = base64_decode($iv);

        $sessionKey = $r['session_key'];
        $aesKey = base64_decode($sessionKey);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        Log::info("解密 包". $result);

        $data = json_decode($result, true);

        $wxConfig = config('weixin');
        $appId = $wxConfig['micro_app_id'];
        if ($appId != $data['watermark']['appid']) {
            return false;
        }

        return $data;
    }

    public static function microOauth2($code)
    {
        //$wxConfig = Config::get('wx_micro_app');
        $wxConfig = config('weixin');
        $appId = $wxConfig['micro_app_id'];

// https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

        $url = 'https://api.weixin.qq.com/sns/jscode2session?'
            .'appid=' . $appId
            .'&secret=' . $wxConfig['micro_secret_key']
            .'&js_code=' . $code
            .'&grant_type=authorization_code';

        $r = http_get_json($url);

        $log = <<<LOG
weixin-micro-oauth2--------
url: $url
res: $r
LOG;
        Log::info($log);
        $r = @json_decode($r, true);

        if (!isset($r['openid'])) {
            return false;
        }

        return $r;
    }

    /**
     * 创建用户
     * @param $userProfile
     */
    public function createUser($userProfile)
    {
        $user = new UserModel();
        !empty($userProfile['nickname']) && $user->nickname = $userProfile['nickname'];
        !empty($userProfile['unionid']) && $user->union_id = $userProfile['unionid'];
        $user->open_id = $userProfile['openid'];

        !empty($userProfile['headimgurl']) && $user->avatar = $userProfile['headimgurl'];

        $user->is_active = 0;
        $user->save();

        return $user->toArray();
    }

    public function getAccessToken()
    {
        $token = Redis::get('wx:access_token');
        if (empty($token)) {
            $wxConfig = config('weixin');
            $appId = $wxConfig['micro_app_id'];
            $appSecret = $wxConfig['micro_secret_key'];

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            $r = http_get_json($url);

            $r = @json_decode($r, true);
            Redis::set('wx:access_token', $r['access_token']);
            Redis::expire('wx:access_token', 7100);

            return $r['access_token'];
        } else {
            return $token;
        }
    }

    /**
     * 给用户推送小程序消息
     * @param $openId
     * @param $msg
     */
    public function pushMicroMsg($openId, $formId, BaseMicroMsg $msg)
    {
        $token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={$token}";

        $payload = [
            'touser' => $openId,
            'template_id' => $msg->getTemplateId(),
            'form_id' => $formId,
            'data' => $msg->getData(),
            'page' => 'pages/home/home',
        ];

        //Log::info("openid {$openId} 推送消息" . json_encode($payload));
        //$ret = http_post_json($url, $payload);

    }
}

